package com.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.service.edu.pojo.Comment;
import com.service.edu.mapper.CommentMapper;
import com.service.edu.pojo.Teacher;
import com.service.edu.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.edu.service.CourseService;
import com.service.utils.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-10-07
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CourseService courseService;

    @Override
    public ResultVo pages(Integer pageNum, Integer rows, Comment comment) {

        // 构建查询条件
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        //声明分页对象 pageNum：当前页数   rows:每页显示条数
        Page<Comment> page = new Page<>(pageNum,rows);
        //判断查询条件是否为空
        if (comment==null){
            //如果为空则分页  不做查询
            this.page(page, null);
        }else{
            //判断content是否为空
            if (!StringUtils.isEmpty(comment.getContent())){
                //如果不为空  则模糊查询name
                queryWrapper.like("content",comment.getContent());
            }
            if (!StringUtils.isEmpty(comment.getTeacherId())){
                queryWrapper.eq("teacher_id",comment.getTeacherId());
            }
            if (!StringUtils.isEmpty(comment.getCourseId())){
                queryWrapper.orderByDesc("gmt_create");
                queryWrapper.eq("course_id",comment.getCourseId());
            }
            this.page(page, queryWrapper);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("pages",page.getPages());
        map.put("pageNum",page.getCurrent());
        List<Comment> list = page.getRecords();
        for (Comment c : list) {
            c.setCourseTitle(courseService.getById(c.getCourseId()).getTitle());
        }
        map.put("items",list);
        return ResultVo.ok().data(map);
    }
}
